package com.sfzd5.exam.helplibrary;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import org.bytedeco.javacpp.indexer.UByteIndexer;
import org.bytedeco.javacpp.opencv_core.*;

import java.io.IOException;
import java.util.Hashtable;

import static org.bytedeco.javacpp.opencv_core.CV_8UC1;


public class QrcodeHelper {

    /**
     * 编码字符串内容到目标File对象中
     *
     * @param encodeddata 编码的内容
     * @throws IOException
     */
    public static Mat qrCodeEncode(String encodeddata, int size) throws WriterException {
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix matrix = new MultiFormatWriter().encode(encodeddata, BarcodeFormat.QR_CODE, size, size);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        Mat mat = new Mat(width, height, CV_8UC1);
        mat.put(Scalar.WHITE);

        UByteIndexer sI = mat.createIndexer();
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    sI.put(x, y, 0);
                } else {
                    sI.put(x, y, 255);
                }
            }
        }
        return mat;
    }
}
